package com.fauks.ssm.springmvc.converter;

import org.springframework.beans.TypeMismatchException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/converter")
public class ConverterController {

    @RequestMapping("/usedate")
    public String testUseDate(String name, Date date, int age, Model model) {
        System.out.println(name);
        System.out.println(date);
        System.out.println(age);
        model.addAttribute("name", name);
        model.addAttribute("date", date);
        model.addAttribute("age", age);
        return "converter";
    }

    @RequestMapping("/validator")
    //@Validated表示要被校验的bean
    //BindingResult存储校验失败后的信息
    public ModelAndView testValidator(@Validated ValidatorBean validatorBean, BindingResult br) {
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(validatorBean);
        //数据校验失败
        List<ObjectError> allErrors = br.getAllErrors();
        if (allErrors != null && allErrors.size() > 0) {
            FieldError nameError = br.getFieldError("name");
            FieldError mobileError = br.getFieldError("mobile");
            if (nameError != null) {
                modelAndView.addObject("nameError", nameError.getDefaultMessage());
            }
            if (mobileError != null) {
                modelAndView.addObject("mobileError", mobileError.getDefaultMessage());
            }
        }
        modelAndView.setViewName("forward:/index.jsp");
        return modelAndView;
    }

    //发生异常时跳转到自定义页面
    //用户表单提交的数据此处无法直接获取，但是可以通过request获取
    @ExceptionHandler(TypeMismatchException.class)
    public ModelAndView exceptionResolver(Exception ex, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        String name = request.getParameter("name");
        String date = request.getParameter("date");
        String age = request.getParameter("age");
        //添加到域对象中然后jsp中会使用EL表达式获取
        modelAndView.addObject("name", name);
        modelAndView.addObject("date", date);
        modelAndView.addObject("age", age);
        //数据输入错误在定向到表单数据页面,显示指定forward不走视图解析器
        modelAndView.setViewName("forward:/index.jsp");
        return modelAndView;
    }
}
